<template>

  <div>


    <el-container>
      <el-header>

        <el-row justify="start">
          <el-col :span="4">
            <div>
              <el-input
                  placeholder="请输入内容"
                  v-model="search"
                  clearable>
              </el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <div>
              <el-button @click="refresh">刷新</el-button>
              <el-button v-show="!systemFlag" @click="add">新增版本</el-button>

              <!--          <el-button @click="clearFilter">清除所有过滤器</el-button>-->
            </div>
          </el-col>
        </el-row>
      </el-header>
      <el-main>

        <el-row justify="start">
          <el-col :span="24">
            <div class="">
              <el-table
                  :data="this.tableData"
                  max-height="250"
                  :onCell-click="this.cellClick"
                  style="width: 100%">
                <el-table-column
                    fixed
                    prop="compCode"
                    label="组件编码">
                </el-table-column>
                <el-table-column
                    prop="compVersion"
                    label="版本">
                </el-table-column>
                <el-table-column
                    prop="compDesc"
                    label="组件描述">
                </el-table-column>


                <el-table-column
                    prop="disableFlag"
                    label="启停状态"
                >
                  <template #default="scope">
                    <el-tag
                        :type="scope.row.disableFlag === '0' ? '启用' : '停用'"
                        disable-transitions
                    >{{ scope.row.disableFlag == '0' ? '启用' : '停用' }}
                    </el-tag
                    >
                  </template>
                </el-table-column>
                <el-table-column
                    prop="buildStatus"
                    label="构建状态"
                >
                  <template #default="scope">
                    <el-tag
                        :type="scope.row.buildStatus === 1 ? '构建中' : scope.row.buildStatus === 2?'构建完成':scope.row.buildStatus === 3?'构建失败':''"
                        disable-transitions
                    >{{
                        scope.row.buildStatus === 1 ? '构建中' : scope.row.buildStatus === 2 ? '构建完成' : scope.row.buildStatus === 3 ? '构建失败' : ''
                      }}
                    </el-tag
                    >
                  </template>
                </el-table-column>
                <el-table-column
                    fixed="right"
                    label="操作"
                    width="400">
                  <template #default="scope">
                    <el-button v-if="!scope.row.systemFlag" @click="setStatusFlag(scope.row)" type="default"
                               size="small">
                      {{ scope.row.disableFlag == '0' ? '停用' : '启用' }}
                    </el-button>

                    <el-button v-if="scope.row.systemFlag" @click="view(scope.row)" type="default" size="small">查看
                    </el-button>
                    <el-button v-if="!scope.row.systemFlag" @click="edit(scope.row)" type="default" size="small">编辑
                    </el-button>
                    <el-button v-if="scope.row.systemFlag" @click="viewPackage(scope.row)" type="default" size="small">
                      查看包
                    </el-button>
                    <el-button v-if="!scope.row.systemFlag" @click="editPackage(scope.row)" type="default" size="small">
                      编辑包
                    </el-button>
                    <el-button v-if="!scope.row.systemFlag" @click="download(scope.row)" type="default" size="small">
                      下载包
                    </el-button>

                    <!--                      <el-button @click="upload(scope.row)" type="default" size="small">上传包</el-button>-->
                    <el-upload v-if="!scope.row.systemFlag"
                               ref="upload"
                               class="upload-demo"
                               :limit="1"
                               :show-file-list="false"
                               :auto-upload="false"
                               :on-change="progress"
                    >
                      <template #trigger>
                        &nbsp; &nbsp;<el-button type="primary">上传包</el-button>
                      </template>
                    </el-upload>
                    <!--                      <el-button type="default" size="small" @click="handleConfig(scope.row)">上传</el-button>-->
                  </template>
                </el-table-column>
              </el-table>

            </div>
          </el-col>
        </el-row>

      </el-main>


      <el-dialog v-model="compDiag.visible" width="300px">
        <el-form :model="compDiag">
          <el-form-item label="组件版本">
            <el-input v-model="compDiag.compVersion" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="组件描述">
            <el-input v-model="compDiag.compDesc" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="初始化demo包">
            <el-checkbox v-model="compDiag.isInitDemoFlag" label="" size="large"/>
          </el-form-item>
          <!--            <el-form-item label="组件包">-->
          <!--              <el-upload-->
          <!--                  ref="upload"-->
          <!--                  class="upload-demo"-->
          <!--                  :limit="1"-->
          <!--                  :auto-upload="false"-->
          <!--                  :on-change="progress"-->
          <!--              >-->
          <!--                <template #trigger>-->
          <!--                  <el-button type="primary">select file</el-button>-->
          <!--                </template>-->
          <!--              </el-upload>-->

          <!--            </el-form-item>-->

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="compDiag.visible = false">取 消</el-button>
          <el-button type="primary" @click="this.saveCompVersion">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog v-model="this.compObjectDiag" width="100%">
        <ProcessCompObjectManager :compCode="this.currentCompCode"
                                  :compVersion="this.currentCompVersion" ref="objManager"/>
        <div>&nbsp;</div>
        <el-button @click="compObjectDiag = false">取 消</el-button>
        <el-button v-show="!systemFlag" type="primary" @click="this.saveObj">确 定</el-button>
      </el-dialog>

      <el-dialog v-model="this.buildDiag" width="100%">
        <div ref="logInput" style="width: 100%; height: 500px;text-align:left;"></div>
        <el-button @click="buildDiag = false">确 定</el-button>
      </el-dialog>
    </el-container>
  </div>

</template>

<script>
import {getStream, post} from '../../config/Request.js'
import {h} from "vue";
import ProcessCompObjectManager from './ProcessCompObjectManager.vue'

import * as monaco from "monaco-editor";
import {toRaw} from 'vue'
import apis from "@/request/apis.js";

export default {
  name: "ProcessCompVersionManager",
  components: {
    ProcessCompObjectManager
  },
  data() {
    return {
      tableData: [],
      compCode: null,
      compVersionView: false,
      currentCompVersion: null,
      monacoEditor: null,
      buildDiag: false,
      currentCompCode: null,
      systemFlag: false,
      search: null,
      compObjectDiag: false,
      compDiag: {
        visible: false,
        viewFlag: false,
        compVersion: '',
        compCode: '',
        isInitDemoFlag: false,
        id: null,
        compDesc: null
        // compFile: null
      }
    }
  },
  mounted() {
    // this.refresh();
  },
  methods: {
    saveObj() {

      this.$refs.objManager.pack();
      this.compObjectDiag = false;
    },
    refresh(compCode, systemFlag) {
      if (compCode && typeof compCode == 'string') {
        this.compCode = compCode;
      }
      if (systemFlag != null) {
        this.systemFlag = systemFlag;
      }
      this.queryCompVersionList();
    },
    add() {
      this.compDiag.visible = true;

    },
    view(row) {
      this.compDiag.compCode = row.compCode;
      this.compDiag.id = row.id;
      this.compDiag.compDesc = row.compDesc;
      this.compDiag.systemFlag = row.systemFlag;
      this.compDiag.viewFlag = true;
      this.compDiag.compVersion = row.compVersion;
      this.compDiag.visible = true;
    },
    async download(row) {
      var blob = await getStream("/square-lake/process/comp/object/get_file?compCode=" + row.compCode + "&compVersion=" + row.compVersion);
      var downloadElement = document.createElement('a');
      var href = window.URL.createObjectURL(blob); //创建下载的链接
      downloadElement.href = href;
      downloadElement.download = row.compCode + "@" + row.compVersion + "@" + ".zip"; //定义文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); //点击下载
      document.body.removeChild(downloadElement); //下载完成移除元素
      window.URL.revokeObjectURL(href); //释放掉blob对象
    },
    clearLog() {
      toRaw(this.monacoEditor).setValue("");

    },
    async viewPackage(row) {
      this.editPackage(row);
    },
    editPackage(row) {
      this.compObjectDiag = true;
      setTimeout(function () {
        this.$refs.objManager.loadZip(row.compCode, row.compVersion,false,false);
      }.bind(this), 0)
    },
    cellClick(row, column) {
      this.currentCompVersion = row.compVersion;
      this.currentCompCode = row.compCode;
      if (column.property == 'buildStatus') {
        this.buildDiag = true;
        setTimeout(function () {

          this.initMonaco();
          this.clearLog();
          this.getBuildLog(row);
        }.bind(this), 0)

      }
    },
    async getBuildLog(row) {
      const d = await apis.post("/square-lake/process/comp/version/build/get_last_by_code_and_version", {
        compVersion: row.compVersion, compCode: row.compCode
      });
      if (d && d.buildContent) {
        toRaw(this.monacoEditor).setValue(d.buildContent);
      }
    },
    initMonaco() {
      if (this.monacoEditor == null) {
        this.monacoEditor = monaco.editor.create(this.$refs.logInput, {
          theme: "vs-dark", // 主题
          value: "", // 默认显示的值
          language: "log",
          folding: true, // 是否折叠
          foldingHighlight: true, // 折叠等高线
          foldingStrategy: "indentation", // 折叠方式  auto | indentation
          showFoldingControls: "always", // 是否一直显示折叠 always | mouseover
          disableLayerHinting: true, // 等宽优化
          emptySelectionClipboard: false, // 空选择剪切板
          selectionClipboard: false, // 选择剪切板
          automaticLayout: true, // 自动布局
          codeLens: false, // 代码镜头
          scrollBeyondLastLine: false, // 滚动完最后一行后再滚动一屏幕
          colorDecorators: true, // 颜色装饰器
          accessibilitySupport: "off", // 辅助功能支持  "auto" | "off" | "on"
          lineNumbers: "on", // 行号 取值： "on" | "off" | "relative" | "interval" | function
          lineNumbersMinChars: 5, // 行号最小字符   number
          enableSplitViewResizing: false,
          readOnly: false, //是否只读  取值 true | false
        });
      }
    },
    async progress(file) {
      let reader = new FileReader()
      // abort none 中断读取
      // readAsBinaryString file 将文件读取为二进制码，通常我们将它传送到后端，后端可以通过这段字符串存储文件
      // readAsDataURL file 将文件读取为 DataURL，一段以 data: 开头的字符串，这段字符串的实质就是 Data URL，Data URL是一种将小文件直接嵌入文档的方案。这里的小文件通常是指图像与 html 等格式的文件
      // readAsText file, [encoding] 将文件读取为文本，读取的结果即是这个文本文件中的内容
      reader.readAsDataURL(file.raw)
      // onabort 中断时触发
      // onerror 出错时触发
      // onload 文件读取成功完成时触发
      // onloadend 读取完成触发，无论成功或失败
      // onloadstart 读取开始时触发
      // onprogress 读取中
      const s = this;
      reader.onload = (e) => {
        // 读取文件内容
        // s.compDiag.icon = e.target.result;
        s.saveFile(e.target.result);
        // s.svgToBase64();
        // 接下来可对文件内容进行处理
      }
    },

    saveFile(file) {
      apis.post("/square-lake/process/comp/object/save", {
        compVersion: this.currentCompVersion, compCode: this.currentCompCode,
        compFile: file
      });
      this.$notify({
        title: '提示',
        message: h('i', {style: 'color: teal'}, '上传成功')
      });
    },
    async setStatusFlag(row) {
      await apis.post("/square-lake/process/comp/version/set_status_flag", {
        id: row.id, disableFlag:
            row.disableFlag == '1' ? '0' : '1'
      });
      this.refresh();
    },
    async edit(row) {
      const data = await apis.post("/square-lake/process/comp/version/get_by_id", {id: row.id, version: row.version});
      this.compDiag.compCode = data.compCode;
      this.compDiag.id = data.id;
      this.compDiag.compDesc = data.compDesc;
      this.compDiag.compVersion = data.compVersion;
      this.compDiag.visible = true;
    },
    async saveCompVersion() {
      if (this.compDiag.viewFlag) {
        this.compDiag.viewFlag = false;
        this.compDiag.visible = false;
        return
      }
      if (!this.compCode) {
        this.$message.error('错误操作，没有获取到组件编码');
        return;
      }
      this.compDiag.compCode = this.compCode;

      if (!this.compDiag.compVersion) {
        this.$message.error('请输入组件版本');
        return;
      }
      // if (!this.compDiag.compFile) {
      //   this.$message.error('请选择组件包');
      //   return;
      // }
      await apis.post("/square-lake/process/comp/version/save", {
        compCode: this.compDiag.compCode,
        compVersion: this.compDiag.compVersion,
        compDesc: this.compDiag.compDesc,
        isInitDemoFlag: this.compDiag.isInitDemoFlag,
        // compFile: this.compDiag.compFile,
        id: this.compDiag.id
      });

      this.compDiag.compVersion = '';
      this.compDiag.compCode = '';
      this.compDiag.compDesc = '';
      // this.compDiag.compFile = '';
      this.compDiag.visible = false;
      this.compDiag.id = null;
      this.refresh();
    },
    async queryCompVersionList() {
      const data = await apis.post("/square-lake/process/comp/version/list", {
        compCode: this.compCode
      })
      // console.log(data);
      // this.$set(this, "tableData", data);
      this.tableData = data;
    }
  }
}
</script>

<style scoped>

.upload-demo {
  display: inline;
}

</style>